import { defineStore } from "pinia";
import { AuthState } from "@/stores/interface";
import { getFlatMenuList, getShowMenuList, getAllBreadcrumbList } from "@/utils";
import allRoute from "@/assets/routerMenuList/index";

// import { useUserStore } from "@/stores/modules/user";
// import { AuthFuncMenu } fconsole.log(1);rom "@/api/interface/auth/funcMenu";
export const useAuthStore = defineStore({
  id: "geeker-auth",
  state: (): AuthState => ({
    // 按钮权限列表
    authButtonList: [],
    // 菜单权限列表
    authMenuList: [],
    // 当前页面的 router name，用来做按钮权限筛选
    routeName: "",
    // 用户角色
    roles: []
  }),
  getters: {
    // 按钮权限列表
    authButtonListGet: state => state.authButtonList,
    // 菜单权限列表 ==> 这里的菜单没有经过任何处理
    authMenuListGet: state => state.authMenuList,
    // 菜单权限列表 ==> 左侧菜单栏渲染，需要剔除 isHide == true
    showMenuListGet: state => getShowMenuList(state.authMenuList),
    // 菜单权限列表 ==> 扁平化之后的一维数组菜单，主要用来添加动态路由
    flatMenuListGet: state => getFlatMenuList(state.authMenuList),
    // 递归处理后的所有面包屑导航列表
    breadcrumbListGet: state => getAllBreadcrumbList(state.authMenuList)
  },
  actions: {
    // 获取用户权限
    async getAuthBySysUser() {
      // const userStore = useUserStore();
      // 获取用户权限
      // const { buttonList, menuList, roleList } = await getAuthBySysUser({ username: userStore.username });
      // console.log(setDynamicRoute);

      // await setDynamicRoute();
      // 过滤出可显示的路由
      this.authMenuList = filterAsyncRoutes(allRoute, []);

      // 获取用户角色
      // this.roles = roleList || [];

      // 获取用户按钮权限
      // this.authButtonList = buttonList || [];
    },
    // Set RouteName
    async setRouteName(name: string) {
      this.routeName = name;
    }
  }
});

/**
 * 使用 meta.role 以确定当前用户是否具有权限
 * @param roles
 * @param route
 */
const hasPermission = (roles: string[], route: Menu.MenuOptions) => {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles?.includes(role));
  } else {
    return true;
  }
};

/**
 * 通过递归过滤异步路由表
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes: Menu.MenuOptions[], roles: string[]) {
  let res: Menu.MenuOptions[] = [];
  routes.forEach(route => {
    const tmp = { ...route };
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles);
      }
      res.push(tmp);
    }
  });

  return res;
}
/**
 * @description: 将后端路由放置到菜单上
 * @return {*}
 */
// const setDynamicRoute = async () => {
//   const params = {
//     id: useGlobalStore().systemCode
//   };
//   const data = await funcMenuFindBySystem(params);

//   for (let item of data) {
//     item.children = item.childrenList?.map(children => {
//       const newChildren = setDynamicRouteParams(children);
//       return newChildren;
//     });
//     const newItem = setDynamicRouteParams(item);
//     allRoute.unshift(newItem);
//   }
// };

// const setDynamicRouteParams = (item: AuthFuncMenu.ResSearch) => {
//   const setBoolean = (flag: number): boolean => {
//     return flag !== 0;
//   };

//   const {
//     path,
//     name,
//     redirect,
//     component,
//     icon,
//     title,
//     activeMenu,
//     flagLink,
//     flagHide,
//     flagFull,
//     flagAffix,
//     flagKeepAlive,
//     roleKey,
//     setJson,
//     children
//   } = item || {};

//   const obj: any = {
//     path,
//     name,
//     component,
//     redirect,
//     children,
//     meta: {
//       icon,
//       title,
//       activeMenu,
//       isLink: flagLink || "",
//       isHide: setBoolean(flagHide),
//       isFull: setBoolean(flagFull),
//       isAffix: setBoolean(flagAffix),
//       isKeepAlive: setBoolean(flagKeepAlive),
//       setJson
//     }
//   };
//   if (roleKey) {
//     obj.meta.roles = [roleKey as string];
//   }

//   return obj;
// };
